import cv2
import numpy as np


a =cv2.imread('image/chapter_stage_1.jpg')
# a =cv2.cvtColor(cv2.imread('image/energy.jpg'), cv2.COLOR_BGR2GRAY)
b =cv2.imread('screenshots/Screenshot_2025-01-05-01-49-24-618_com.softstargames.shadow.jpg')
# b =cv2.cvtColor(cv2.imread('screenshots/screenshots.jpg'), cv2.COLOR_BGR2GRAY)

result = cv2.matchTemplate(b, a, cv2.TM_CCOEFF_NORMED)
# 设置阈值
threshold = 0.85
# 在原始图像中绘制匹配到的目标图像位置

print(f'result = {result}')
loc = np.where(result >= 0.8)


h, w = a.shape[:2]
print(a.shape)

# 执行模板匹配


loc = np.where(result >= threshold)
new_width = int(b.shape[1] * 0.5)
new_height = int(b.shape[0] * 0.5)
# 在原图上绘制矩形框标记匹配区域
for pt in zip(*loc[::-1]):
    print(pt)
    cv2.rectangle(b, pt, (pt[0] + w, pt[1] + h), (0, 255, 0), 2)
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result)
# pt = zip(*loc[::-1])
# result = cv2.matchTemplate(b, a, cv2.TM_CCOEFF_NORMED)

#
locations = []
# for i in range(result.shape[0]):
#     for j in range(result.shape[1]):
#         print(max_val, min_val, max_loc, min_loc)
#         if result[i, j] >= threshold * max_val:
#             # locations.append((j + a.shape[1], i + a.shape[0]))
#             locations.append((j, i ))
# print(f'locations={locations}')
i = 0
print('loc = {}'.format(loc))

for pt in zip(*loc[::-1]):
    print(pt)
    locations.append((pt[0].item()+int(w/2),pt[1].item()+int(h/2)))
    # cv2.rectangle(b, pt, (pt[0] + int(w/2), pt[1] +int(h/2)), (0, 255, 0), 2)


print(f'locations = {locations}')


# 显示结果
cv2.namedWindow('Detected', cv2.WINDOW_NORMAL)
cv2.resizeWindow('Detected', new_width, new_height)
cv2.imshow('Detected', b)
cv2.waitKey(0)
cv2.destroyAllWindows()




